$(function () {
    // 全局变量存储当前视图状态
    var currentLevel = 'province'; // 'province' 或 'county'
    var currentCityCode = null;
    var currentCityName = null;
    var provinceData = null;
    var myChart = null;

    // 调用getMapData获取数据并初始化地图
    getMapData(function(err, res) {
        if (err) {
            console.error('获取地图数据失败:', err);
            return;
        }
        
        // 成功获取数据后初始化地图
        if (res && res.code === "SUCCESS" && res.data) {
            // 保存原始省级数据
            provinceData = res.data;
            
            // 使用format.js中的逻辑处理地图数据和坐标
            processMapData(res.data).then(function(processedData) {
                // 确保中国地图已加载
                loadChinaMap();
                map(processedData);
            }).catch(function(error) {
                console.error('处理地图数据失败:', error);
            });
        } else {
            console.error('地图数据格式不正确:', res);
        }
    });
    
    // 加载中国地图
    function loadChinaMap() {
        // ECharts已内置中国地图，此处检查必要的地图组件是否存在
        if (!echarts.getMap('china')) {
            console.error('中国地图未加载，这可能导致显示问题');
        }
    }
    
    // 处理地图数据，获取坐标信息
    async function processMapData(data) {
        const map = {};
        const valueData = [];
        
        // 先加载直辖市数据
        let zhixiashis;
        try {
            zhixiashis = await $.getJSON('static/json/zhixiashi.json');
        } catch (error) {
            console.error('加载直辖市数据失败:', error);
            zhixiashis = [];
        }
        
        for (let i = 0; i < data.length; i++) {
            const res = data[i];
            const { provinceCode, cityCode, cityName, count, areaCode, areaName } = res;
            
            // 查找是否为直辖市
            const findCity = zhixiashis.find(zxs => zxs.properties.adcode == provinceCode);
            let center;
            
            // 直辖市
            if (findCity) {
                center = findCity.properties.center;
            } else {
                try {
                    // 加载省级地图数据
                    var { features } = await $.getJSON(`static/json/map/province/${provinceCode}.json`);
                    const findCity = features.find(city => cityCode == city.properties.adcode);
                    
                    if (findCity && findCity.properties) {
                        center = findCity.properties.center;
                    } else {
                        console.warn(`未找到城市坐标: ${cityName}(${cityCode})`);
                        continue;
                    }
                } catch (error) {
                    console.error(`加载省级地图数据失败: ${provinceCode}`, error);
                    continue;
                }
            }
            
            if (center) {
                map[cityName] = center;
                valueData.push({ 
                    name: cityName, 
                    value: count,
                    cityCode: cityCode,
                    provinceCode: provinceCode,
                    areaCode: areaCode,
                    areaName: areaName
                });
            }
        }
        
        return { geoCoordMap: map, data: valueData };
    }
    
    // 处理区县级别数据并加载区县地图
    async function processCountyData(cityCode, cityName) {
        try {
            
            // 判断是否为直辖市，需要根据数据中的provinceCode字段
            // 直辖市的province代码：北京110000, 天津120000, 上海310000, 重庆500000
            const directCityCodes = ['110000', '120000', '310000', '500000'];
            const cityData = provinceData.find(item => item.cityCode === cityCode);
            const isDirectCity = cityData && directCityCodes.includes(cityData.provinceCode);
            const provinceCode = cityData ? cityData.provinceCode : cityCode.substring(0, 2) + '0000';
            
            
            // 加载城市下的区县数据
            let citysJson;
            try {
                if (isDirectCity) {
                    // 直辖市直接从province目录加载省级地图
                    citysJson = await $.getJSON(`static/json/map/province/${provinceCode}.json`);
                    console.log('从province目录加载直辖市数据:', citysJson);
                } else {
                    // 普通城市从citys目录加载
                    citysJson = await $.getJSON(`static/json/map/citys/${cityCode}.json`);
                    console.log('从citys目录加载城市数据:', citysJson);
                }
            } catch (error) {
                console.error(`区县JSON加载失败, 尝试备用路径: ${isDirectCity ? provinceCode : cityCode}`, error);
                try {
                    if (isDirectCity) {
                        // 直辖市没有备用路径，因为省级地图是唯一的
                        throw new Error(`无法加载直辖市数据: ${provinceCode}`);
                    } else {
                        // 普通城市尝试county目录
                        citysJson = await $.getJSON(`static/json/map/county/${cityCode}.json`);
                        console.log('备用路径成功加载区县JSON:', citysJson);
                    }
                } catch (secondError) {
                    console.error(`备用路径加载失败: ${isDirectCity ? provinceCode : cityCode}`, secondError);
                    throw new Error(`无法加载区县数据: ${isDirectCity ? provinceCode : cityCode}`);
                }
            }
            
            // 确保数据格式正确
            if (!citysJson || !citysJson.features) {
                console.error('区县JSON格式不正确:', citysJson);
                throw new Error(`区县JSON格式不正确: ${isDirectCity ? provinceCode : cityCode}`);
            }
            
            // 注册区县地图到ECharts
            try {
                const mapCode = isDirectCity ? provinceCode : cityCode;
                echarts.registerMap(mapCode, citysJson);
            } catch(e) {
                console.error(`注册地图失败: ${isDirectCity ? provinceCode : cityCode}`, e);
                throw e;
            }
            
            const features = citysJson.features;
            const map = {};
            const valueData = [];
            
            // 对于当前城市下的每个区县
            for (let i = 0; i < features.length; i++) {
                const county = features[i];
                if (county.properties && county.properties.center && county.properties.name) {
                    const countyName = county.properties.name;
                    const countyCode = county.properties.adcode;
                    map[countyName] = county.properties.center;
                    
                    // 查找API返回的区县数据
                    let countyData = null;
                    
                    if (isDirectCity) {
                        // 直辖市的区县数据匹配：同一个provinceCode下的areaCode或areaName
                        countyData = provinceData.find(item => 
                            item.provinceCode === provinceCode && 
                            (item.areaCode === countyCode || item.areaName === countyName)
                        );
                    } else {
                        // 普通城市的区县数据匹配：同一个cityCode下的areaCode或areaName
                        countyData = provinceData.find(item => 
                            item.cityCode === cityCode && 
                            (item.areaCode === countyCode || item.areaName === countyName)
                        );
                    }
                    
                    
                    const count = countyData ? countyData.count : 0;
                    
                    valueData.push({
                        name: countyName,
                        value: count,
                        countyCode: countyCode
                    });
                }
            }
            
            return { 
                geoCoordMap: map, 
                data: valueData, 
                cityName: cityName,
                cityCode: isDirectCity ? provinceCode : cityCode, // 使用正确的代码作为地图ID
                mapData: citysJson 
            };
        } catch (error) {
            console.error(`加载区县数据失败: ${cityCode}`, error);
            alert(`加载区县数据失败: ${error.message}`);
            throw error;
        }
    }
    
    function map(processedData) {
        // 基于准备好的dom，初始化echarts实例
        if (!myChart) {
            myChart = echarts.init(document.getElementById('map'));
        } else {
            myChart.dispose();
            myChart = echarts.init(document.getElementById('map'));
        }
        
        // 使用处理好的数据
        var data = processedData.data;
        var geoCoordMap = processedData.geoCoordMap;
        
        var convertData = function (data) {
            var res = [];
            for (var i = 0; i < data.length; i++) {
                var geoCoord = geoCoordMap[data[i].name];

                if (geoCoord && data[i].value > 0) {  // 只显示值大于0的点
                    res.push({
                        name: data[i].name,
                        value: geoCoord.concat(data[i].value),
                        cityCode: data[i].cityCode,
                        provinceCode: data[i].provinceCode,
                        areaCode: data[i].areaCode,
                        areaName: data[i].areaName,
                        count: data[i].value
                    });
                }
            }
            return res;
        };

        var option;
        if (currentLevel === 'province') {
            // 全国地图配置
            option = {
                title: {
                    text: '全国合伙人分布',
                    left: 'center',
                    textStyle: {
                        color: '#fff'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return params.name + ': ' + (params.value && params.value[2] ? params.value[2] : 0);
                    }
                },
                geo: {
                    map: 'china',
                    label: {
                        emphasis: {
                            show: false
                        }
                    },
                    roam: true,
                    zoom: 1.2,
                    itemStyle: {
                        normal: {
                            areaColor: 'rgba(2,37,101,.5)',
                            borderColor: 'rgba(112,187,252,.5)'
                        },
                        emphasis: {
                            areaColor: 'rgba(2,37,101,.8)'
                        }
                    }
                },
                series: [
                    {
                        name: '合伙人数量',
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        data: convertData(data),
                        symbolSize: function (val) {
                            return val[2] / 5 + 8;
                        },
                        label: {
                            normal: {
                                formatter: '{b}',
                                position: 'right',
                                show: false
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: '#ffeb7b'
                            }
                        }
                    }
                ]
            };
        } else {
            // 区县地图配置
            option = {
                title: {
                    text: currentCityName + '区县合伙人分布',
                    left: 'center',
                    textStyle: {
                        color: '#fff'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        var value = params.value;
                        if (Array.isArray(value)) {
                            return params.name + ': ' + value[2];
                        } else {
                            return params.name + ': ' + (value || 0);
                        }
                    }
                },
                geo: {
                    map: currentCityCode,
                    roam: true,
                    zoom: 1.5,
                    label: {
                        normal: {
                            show: true,
                            textStyle: {
                                color: '#fff'
                            }
                        },
                        emphasis: {
                            show: true
                        }
                    },
                    itemStyle: {
                        normal: {
                            areaColor: 'rgba(2,37,101,.5)',
                            borderColor: 'rgba(112,187,252,.5)'
                        },
                        emphasis: {
                            areaColor: 'rgba(2,37,101,.8)'
                        }
                    }
                },
                series: [
                    {
                        name: '合伙人数量',
                        type: 'scatter',
                        coordinateSystem: 'geo',
                        data: data.map(function(item) {
                            // 使用区县中心点和数值创建散点数据
                            const geoCoord = geoCoordMap[item.name];
                            // 过滤掉值为0的数据点
                            if (geoCoord && item.value > 0) {
                                return {
                                    name: item.name,
                                    value: geoCoord.concat(item.value),
                                    countyCode: item.countyCode
                                };
                            }
                            return null;
                        }).filter(item => item !== null),
                        symbolSize: function (val) {
                            if(val[2]>500){
                                return 50
                            }
                            if(val[2]<50){
                                return 5
                            }
                            return val[2] / 10;
                        },
                        label: {
                            normal: {
                                formatter: '{b}',
                                position: 'right',
                                show: false
                            },
                            emphasis: {
                                show: true
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: '#ffeb7b'
                            }
                        }
                    }
                ]
            };
        }

        myChart.setOption(option, true);
        
        // 添加点击事件，查看区县数据
        if (currentLevel === 'province') {
            myChart.on('click', function(params) {
                if (params.data && params.data.cityCode) {
                    showCountyData(params.data.cityCode, params.name);
                }
            });
        } else {
            // 添加返回按钮
            if (!document.getElementById('backToProvince')) {
                var backBtn = document.createElement('button');
                backBtn.id = 'backToProvince';
                backBtn.innerHTML = '返回省级视图';
                backBtn.style = 'position: absolute; top: 10px; right: 10px; z-index: 100; padding: 5px 10px; background: rgba(0,0,0,0.5); color: white; border: none; border-radius: 4px;';
                document.getElementById('map').parentNode.appendChild(backBtn);
                
                backBtn.addEventListener('click', function() {
                    if (document.getElementById('backToProvince')) {
                        document.getElementById('backToProvince').remove();
                    }
                    showProvinceData();
                });
            }
        }
        
        window.addEventListener("resize", function () {
            myChart.resize();
        });
    }
    
    // 显示区县数据
    function showCountyData(cityCode, cityName) {
        currentLevel = 'county';
        currentCityCode = cityCode;
        currentCityName = cityName;
        
        
        // 判断是否为直辖市，需要处理cityCode
        const directCityCodes = ['110000', '120000', '310000', '500000'];
        const cityData = provinceData.find(item => item.cityCode === cityCode);
        if (cityData && directCityCodes.includes(cityData.provinceCode)) {
            // 如果是直辖市，使用provinceCode替代cityCode
            currentCityCode = cityData.provinceCode;
        }
        
        processCountyData(cityCode, cityName).then(function(processedData) {
            map(processedData);
        }).catch(function(error) {
            console.error('处理区县数据失败:', error);
            // 失败时返回省级视图
            showProvinceData();
        });
    }
    
    // 返回省级视图
    function showProvinceData() {
        currentLevel = 'province';
        currentCityCode = null;
        currentCityName = null;
        
        
        // 使用format.js中的逻辑处理地图数据和坐标
        processMapData(provinceData).then(function(processedData) {
            map(processedData);
        }).catch(function(error) {
            console.error('处理地图数据失败:', error);
        });
    }
})

